package com.wtf.dsp.admin.service.impl;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.wtf.dsp.admin.constant.Constants;
import com.wtf.dsp.admin.enums.CommonErrorEnum;
import com.wtf.dsp.admin.exception.WtfDspException;
import com.wtf.dsp.admin.interceptor.AuthContextHolder;
import com.wtf.dsp.admin.model.LoginUser;
import com.wtf.dsp.admin.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {
    // 令牌自定义标识
    @Value("${token.header:Authorization}")
    private String tokenHeader;

    @Value("${token.signer.key:wtf@1#3}")
    private String tokenSignerKey;

    @Value("${token.exp:7}")
    private int loginTokenExp;

    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotBlank(token))
        {
            boolean verify = false;
            try {
                verify = JWTUtil.verify(token, tokenSignerKey.getBytes());
            } catch (Exception e){
                log.error("JWT Verify Error " + e.getMessage(),e);
            }
            if(verifyTokenDate(token,true) && verify){
                LoginUser loginUser = new LoginUser();
                loginUser.setUsername((String)JWT.of(token).getPayload(Constants.JWT_USERID));
                AuthContextHolder.getInstance().setContext(loginUser);
                return loginUser;
            }
        }
        return null;
    }

    @Override
    public String getToken(String username) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("user",username);
        payload.put("iss","wtf");
        payload.put("exp",new Date(System.currentTimeMillis() + (loginTokenExp * 1000L * 60 * 60 * 24)));
        return JWTUtil.createToken(payload,tokenSignerKey.getBytes());
    }

    private boolean verifyTokenDate(String token, boolean throwException) {
        try{
          JWTValidator.of(token).validateDate(new Date());
          return true;
        } catch (Exception e){
            if(throwException && e instanceof ValidateException ){
                throw new WtfDspException(CommonErrorEnum.ERROR_LOGIN_EXP);
            } else {
                return false;
            }
        }
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }
}
